package com.fcant.ssmcom.controller;

import com.fcant.ssmcom.bean.Course;
import com.fcant.ssmcom.bean.Page;
import com.fcant.ssmcom.bean.User;
import com.fcant.ssmcom.service.CourseService;
import com.fcant.ssmcom.service.UserService;
import com.fcant.ssmcom.utils.FcantUtils;
import com.fcant.ssmcom.utils.MsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.List;

/**
 * UserController
 * <p>
 * encoding:UTF-8
 *
 * @author Fcscanf
 * @description
 * @date 下午 19:35 2019-08-06/0006
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    CourseService courseService;

    @ResponseBody
    @RequestMapping("/add")
    public MsgUtil addUser(User user) {
        int i = userService.addUser(user);
        if (i == 1) {
            return MsgUtil.success();
        } else {
            MsgUtil msgUtil = new MsgUtil();
            if (i == 4) {
                msgUtil.setMsg("邮箱格式错误，请输入正确的邮箱！");
            } else if (i == 5){
                msgUtil.setMsg("手机号格式错误，请输入正确的手机号！");
            }else {
                msgUtil.setMsg("当前学号已经存在，请换更新的学号再添加！");
            }
            msgUtil.setCode(200);
            return msgUtil;
        }
    }

    /**
     * 根据学号查询学生选择的课程信息
     *
     * @param page 接口调用须为必要属性赋值：pageNumber、size、user.number
     * @return ModelAndView
     * @author Fcscanf
     * @date 上午 11:41 2019-08-10/0010
     */
    @RequestMapping("/sc")
    public ModelAndView queryCourseByStuNum(Page page) {
        ModelAndView modelAndView = new ModelAndView();
        // 页面防越界处理
        page = FcantUtils.setPageManager(page);
        List<Course> courses = courseService.queryCourseByNumber(page);
        page.setData(courses);
        page.setTotal(courseService.queryCourseByNumberTotal(page).size());
        modelAndView.addObject("page", page);
        modelAndView.setViewName("student/student");
        return modelAndView;
    }

    /**
     * 查询教师的本学期课程信息
     * @param page 接口调用须为必要属性赋值：pageNumber、size、user.number
     * @return ModelAndView
     * @author Fcscanf
     * @date 下午 14:52 2019-08-09/0009
     */
    @RequestMapping("/tc")
    public ModelAndView queryCourseByTid(Page page) {
        ModelAndView modelAndView = new ModelAndView();
        // 页面防越界处理
        page = FcantUtils.setPageManager(page);
        page.setTotal(courseService.selectByTid(page.getUser()).size());
        page.setData(courseService.queryPageByTid(page));
        modelAndView.addObject("page", page);
        modelAndView.setViewName("teacher/teacher");
        return modelAndView;
    }

    /**
     * 根据不同情况分页检索用户信息
     *
     * @param user 接口调用须为必要属性赋值：rId(判断检索那个角色的信息)
     * @param page 接口调用须为必要属性赋值：pageNumber、size
     * @param type 模糊查询的属性
     * @param key 模糊查询的关键字-可空
     * @return ModelAndView
     * @author Fcscanf
     * @date 上午 11:30 2019-08-10/0010
     */
    @RequestMapping("/page")
    public ModelAndView queryUser(User user, Page page, String type, String key) throws NoSuchFieldException, IllegalAccessException {
        ModelAndView modelAndView = new ModelAndView();
        // 通过反射获取属性的名称，再为属性赋值
        Field field = User.class.getDeclaredField(type);
        field.setAccessible(true);
        field.set(user, key);
        // 查询
        page.setUser(user);
        // 页面防越界处理
        page = FcantUtils.setPageManager(page);
        List<User> users = userService.queryUserLikePage(page);
        page.setData(users);
        List<User> userLikes = userService.queryUserLike(user);
        page.setTotal(userLikes.size());
        // 封装
//        PageHelper.startPage(page.getPageNumber(), page.getSize());
//        PageInfo pageInfo = new PageInfo(userLikes, 5);
        modelAndView.addObject("page", page);
        modelAndView.setViewName("admin/admin");
        return modelAndView;
    }

    /**
     * 用户信息更新
     *
     * @param user 接口调用须为必要属性赋值：number
     * @return ModelAndView
     * @author Fcscanf
     * @date 下午 13:36 2019-08-08/0008
     */
    @RequestMapping("/update")
    public ModelAndView updateUser(User user, String repassword, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        if (user.getPassword().equals(repassword)) {
            int i = userService.updateByNumber(user);
            if (i == 1) {
                User byNumber = userService.selectByNumber(user);
                session.setAttribute("user", byNumber);
                modelAndView.addObject("msg", "修改成功！");
                modelAndView.addObject("user", byNumber);
            }else if (i == 4){
                modelAndView.addObject("msg", "邮箱错误，请输入正确的邮箱！");
            }else {
                modelAndView.addObject("msg", "手机号错误，请输入正确的手机号！");
            }
        }else {
            modelAndView.addObject("msg", "两次输入的密码不一致！");
        }
        modelAndView.setViewName("user/edit");
        return modelAndView;
    }

    /**
     * 用户信息查看
     *
     * @param user 接口调用须为必要属性赋值：number
     * @return ModelAndView
     * @author Fcscanf
     * @date 下午 13:39 2019-08-08/0008
     */
    @RequestMapping("/detail")
    public ModelAndView seeDetail(User user) {
        ModelAndView modelAndView = new ModelAndView();
        User byNumber = userService.selectByNumber(user);
        modelAndView.addObject("user", byNumber);
        modelAndView.setViewName("user/edit");
        return modelAndView;
    }

    /**
     * 根据不同的角色ID返回不同的视图模型
     *
     * @param user 接口调用须为必要属性赋值：number
     * @return ModelAndView
     * @author Fcscanf
     * @date 上午 0:12 2019-08-08/0008
     */
    @RequestMapping("/access")
    public ModelAndView reMoAnVe(User user) throws NoSuchFieldException, IllegalAccessException {
        user = userService.selectByNumber(user);
        Page page = new Page();
        page.setSize(5);
        page.setPageNumber(1);
        page.setUser(user);
        switch (user.getrId()) {
            case 1:
                return queryCourseByStuNum(page);
            case 2:
                return queryCourseByTid(page);
            default:
                // 默认登录加载前五条学生信息
                User u = new User();
                u.setrId(1);
                return queryUser(u, page, "number", "");
        }
    }

    /**
     * 用户登录
     *
     * @param user 接口调用须为必要属性赋值：number、password
     * @param session 记录登录的用户信息
     * @return ModelAndView
     * @author Fcscanf
     * @date 下午 13:56 2019-08-10/0010
     */
    @RequestMapping("/login")
    public ModelAndView regUser(User user, HttpSession session) throws NoSuchFieldException, IllegalAccessException {
        ModelAndView modelAndView = new ModelAndView();
        if (user.getNumber() == null || "".equals(user.getNumber())) {
            modelAndView.addObject("msg", "请输入正确的工号/学号！");
            modelAndView.setViewName("login");
            return modelAndView;
        } else {
            // 查询符合条件的用户-检查用户的存在性
            User selectByNumber = userService.selectByNumber(user);
            if (selectByNumber == null) {
                modelAndView.addObject("msg", "未找到符合条件的用户，请输入正确的工号/学号！");
                modelAndView.setViewName("login");
                return modelAndView;
            } else {
                // 校验用户的密码信息
                if (selectByNumber.getPassword().equals(user.getPassword())) {
                    // 用户名密码正确则根据用户类型跳转至不同的管理页面
                    // 将用户信息保存至Session中
                    session.setAttribute("user", selectByNumber);
                    return reMoAnVe(selectByNumber);
                } else {
                    modelAndView.addObject("msg", "请输入正确的密码！");
                    modelAndView.setViewName("login");
                    return modelAndView;
                }
            }
        }
    }

    /**
     * 登出操作
     *
     * @param session 从Session删除登出的用户信息
     * @param model 用于返回页面退出信息
     * @return String
     * @author Fcscanf
     * @date 下午 13:57 2019-08-10/0010
     */
    @RequestMapping(value = "/signOut")
    public String signOut(HttpSession session, Model model) {
        model.addAttribute("msg", "您已退出登录！");
        session.removeAttribute("user");
        return "login";
    }
}
